package edu.biwu.request;/**
 * @author 王俊彪
 * @version 1.0
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/req/upload01")
@MultipartConfig//该注解用于文件上传
public class ReqUploadDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取 一个part接口,part中封闭了上传文件的所有信息
        Part uploadFile = request.getPart("uploadFile");

        String fileName = uploadFile.getSubmittedFileName();
        //获取上传文件的相关信息
        System.out.println(uploadFile.getSubmittedFileName());//获取该文件的文件名
        System.out.println(uploadFile.getContentType());//获取该文件的MIME类型
        System.out.println(uploadFile.getSize());//获取该文件的大小

        //保证每个人的照片不被其他人在服务器上覆盖，要确保照片的唯一性
        String extension = fileName.substring(fileName.lastIndexOf(".")); // .jpg
        String newFileName= UUID.randomUUID()+extension;

        //将上传文件存储在，服务端的某个位置，存储上传文件
        File dir = new File("D://uploadFile");
        if(!dir.exists()){//文件如果不存在就创建
            dir.mkdir();
        }
        //将上传的文件写入到指定位置
        uploadFile.write(dir+"/"+newFileName);
        //上传成功，返回上传成功提示
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(fileName+"上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
